import React, { useState, useEffect } from 'react';
import { useTemplateContext } from '@/contexts/TemplateContext';
import { Template, TemplateParam } from '@/types';
import { toast } from 'sonner';

const TemplateEditorModal: React.FC = () => {
  const { 
    isTemplateEditorOpen, 
    closeTemplateEditor, 
    selectedTemplate,
    addTemplate,
    updateTemplate
  } = useTemplateContext();
  
  const [templateTitle, setTemplateTitle] = useState('');
  const [templateParams, setTemplateParams] = useState<TemplateParam[]>([]);
  const [templateContent, setTemplateContent] = useState('');
  const [isEditing, setIsEditing] = useState(false);
  const [currentTemplateId, setCurrentTemplateId] = useState('');
  
  // 当模态框打开或选中模板变化时初始化表单
  useEffect(() => {
    if (isTemplateEditorOpen) {
      if (selectedTemplate) {
        // 编辑现有模板
        setIsEditing(true);
        setCurrentTemplateId(selectedTemplate.id);
        setTemplateTitle(selectedTemplate.title);
        setTemplateParams([...selectedTemplate.params]);
        setTemplateContent(selectedTemplate.content);
      } else {
        // 添加新模板
        setIsEditing(false);
        setCurrentTemplateId('');
        setTemplateTitle('');
        setTemplateParams([{ name: '', label: '', type: 'text' }]);
        setTemplateContent('');
      }
    }
  }, [isTemplateEditorOpen, selectedTemplate]);
  
  const handleAddParam = () => {
    setTemplateParams([...templateParams, { name: '', label: '', type: 'text' }]);
  };
  
  const handleRemoveParam = (index: number) => {
    if (templateParams.length <= 1) return;
    
    const newParams = [...templateParams];
    newParams.splice(index, 1);
    setTemplateParams(newParams);
  };
  
  const handleParamChange = (index: number, field: keyof TemplateParam, value: string) => {
    const newParams = [...templateParams];
    newParams[index] = { ...newParams[index], [field]: value };
    setTemplateParams(newParams);
  };
  
  const validateForm = (): boolean => {
    if (!templateTitle.trim()) {
      toast.error('请输入模板名称');
      return false;
    }
    
    for (const param of templateParams) {
      if (!param.name.trim() || !param.label.trim()) {
        toast.error('请完善所有参数信息');
        return false;
      }
    }
    
    if (!templateContent.trim()) {
      toast.error('请输入模板内容');
      return false;
    }
    
    return true;
  };
  
  const handleSaveTemplate = () => {
    if (!validateForm()) return;
    
    const templateData = {
      title: templateTitle,
      params: templateParams,
      content: templateContent
    };
    
    if (isEditing) {
      // 更新现有模板
      updateTemplate({
        id: currentTemplateId,
        ...templateData
      });
      toast.success('模板更新成功');
    } else {
      // 添加新模板
      addTemplate(templateData);
      toast.success('模板添加成功');
    }
    
    closeTemplateEditor();
  };
  
  if (!isTemplateEditorOpen) return null;
  
  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
        <div className="p-6 border-b border-gray-200">
          <h2 className="text-2xl font-bold text-gray-800">
            {isEditing ? '编辑模板' : '添加新模板'}
          </h2>
        </div>
        
        <div className="p-6 space-y-6">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">模板名称</label>
            <input
              type="text"
              value={templateTitle}
              onChange={(e) => setTemplateTitle(e.target.value)}
              className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="输入模板名称"
            />
          </div>
          
          <div>
            <div className="flex justify-between items-center mb-3">
              <label className="block text-sm font-medium text-gray-700">参数定义</label>
              <button
                onClick={handleAddParam}
                className="text-sm text-blue-600 hover:text-blue-800"
              >
                <i className="fa-solid fa-plus mr-1"></i>添加参数
              </button>
            </div>
            
            <div className="space-y-4">
              {templateParams.map((param, index) => (
                <div key={index} className="flex items-center gap-3 p-3 border border-gray-200 rounded-md">
                  <div className="flex-1">
                    <label className="block text-xs text-gray-500 mb-1">参数名</label>
                    <input
                      type="text"
                      value={param.name}
                      onChange={(e) => handleParamChange(index, 'name', e.target.value)}
                      className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                      placeholder="参数名（用于模板中的占位符）"
                    />
                  </div>
                  
                  <div className="flex-1">
                    <label className="block text-xs text-gray-500 mb-1">显示名称</label>
                    <input
                      type="text"
                      value={param.label}
                      onChange={(e) => handleParamChange(index, 'label', e.target.value)}
                      className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                      placeholder="显示在表单中的标签"
                    />
                  </div>
                  
                  <div className="w-32">
                    <label className="block text-xs text-gray-500 mb-1">参数类型</label>
                    <select
                      value={param.type}
                      onChange={(e) => handleParamChange(index, 'type', e.target.value as any)}
                      className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                    >
                      <option value="text">文本</option>
                      <option value="number">数字</option>
                      <option value="date">日期</option>
                    </select>
                  </div>
                  
                  <button
                    onClick={() => handleRemoveParam(index)}
                    className="text-red-500 hover:text-red-700 p-2"
                    disabled={templateParams.length <= 1}
                  >
                    <i className="fa-solid fa-trash"></i>
                  </button>
                </div>
              ))}
            </div>
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">模板内容</label>
            <textarea
              value={templateContent}
              onChange={(e) => setTemplateContent(e.target.value)}
              className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 min-h-[200px]"
              placeholder="输入模板内容，使用{{参数名}}作为占位符"
            />
            <p className="mt-2 text-xs text-gray-500">
              使用双大括号包裹参数名作为占位符，例如：{'{{参数名}}'}
            </p>
          </div>
        </div>
        
        <div className="p-4 bg-gray-50 rounded-b-lg flex justify-end gap-3">
          <button
            onClick={closeTemplateEditor}
            className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleSaveTemplate}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            保存模板
          </button>
        </div>
      </div>
    </div>
  );
};

export default TemplateEditorModal;